<template>
  <div class="add_channels_wrap">
    <el-button icon="el-icon-microphone" type="primary" @click="showRecord">
      录音
    </el-button>
    <el-dialog
      v-if="recordDialog"
      title="录音"
      :visible.sync="recordDialog"
      :close-on-click-modal="false"
    >
      <el-alert
        :closable="false"
        :title="`录音完成后，点击下载保存至本地。`"
        type="info"
      ></el-alert>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <h1 style="text-align: center">{{ str }}</h1>
          <br />
          <div style="text-align: center">
            <el-button
              type="primary"
              :disabled="rstart"
              plain
              @click="startRecorder"
            >
              开始录音
            </el-button>
            <el-button
              type="primary"
              :disabled="pauseStatus"
              plain
              @click="pauseRecorder"
            >
              暂停录音
            </el-button>
            <el-button type="primary" plain @click="resumeRecorder">
              继续录音
            </el-button>
            <el-button type="info" plain @click="stopRecorder">
              重置录音
            </el-button>
            <el-button type="primary" plain @click="downWAV">下载</el-button>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
  import Recorder from 'js-audio-recorder'
  let recorder = new Recorder({
    sampleBits: 16, // 采样位数，支持 8 或 16，默认是16

    sampleRate: 48000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000

    numChannels: 1, // 声道，支持 1 或 2， 默认是1

    // compiling: false,(0.x版本中生效,1.x增加中) // 是否边录边转换，默认是false
  })
  export default {
    name: 'MyRecord',
    data() {
      return {
        rstart: false, // 标识是否开始录音
        pauseStatus: false, //标识是否暂停录音
        hour: 0,
        minute: 0,
        second: 0,
        ms: 0,
        time: '',
        str: '00:00:00', //显示计时器
        recordDialog: false,
      }
    },
    methods: {
      //计时器补0
      toDub(n) {
        //补0操作
        if (n < 10) {
          return '0' + n
        } else {
          return '' + n
        }
      },
      //暂停计时
      stopTime() {
        clearInterval(this.time)
      },
      //重置计时
      resetTime() {
        //重置
        clearInterval(this.time)
        this.hour = 0
        this.minute = 0
        this.ms = 0
        this.second = 0
        this.str = '00:00:00'
      },
      //定义计时函数
      timer() {
        //定义计时函数
        this.ms = this.ms + 50 //毫秒
        if (this.ms >= 1000) {
          this.ms = 0
          this.second = this.second + 1 //秒
        }
        if (this.second >= 60) {
          this.second = 0
          this.minute = this.minute + 1 //分钟
        }
        if (this.minute >= 60) {
          this.minute = 0
          this.hour = this.hour + 1 //小时
        }
        this.str =
          this.toDub(this.hour) +
          ':' +
          this.toDub(this.minute) +
          ':' +
          this.toDub(this.second) /*+""+this.toDubms(this.ms)+"毫秒"*/

        // document.getElementById('mytime').innerHTML=h+"时"+m+"分"+s+"秒"+ms+"毫秒";
      },
      //开始计时
      timeStart() {
        this.time = setInterval(this.timer, 50)
      },
      // 获取麦克风权限
      // getPermission() {
      //   Recorder.getPermission().then(
      //     () => {
      //       this.$message.success('获取权限成功')
      //     },
      //     (error) => {
      //       console.log(`${error.name} : ${error.message}`)
      //     }
      //   )
      // },
      // 开始录音
      startRecorder() {
        this.rstart = true
        this.timeStart()
        recorder.start().then(
          () => {},
          (error) => {
            // 出错了
            console.log(`${error.name} : ${error.message}`)
          }
        )
      },
      // 继续录音
      resumeRecorder() {
        recorder.resume()
        if (this.rstart && this.pauseStatus) {
          this.timeStart()
          this.pauseStatus = false
        } else if (this.rstart && !this.pauseStatus) {
          this.$message({
            message: '正在进行录音哦！',
            type: 'warning',
          })
        } else {
          this.$message({
            message: '还未开始录音哦！',
            type: 'error',
          })
        }
      },
      // 暂停录音
      pauseRecorder() {
        if (this.rstart) this.pauseStatus = true
        recorder.pause()
        this.stopTime()
      },
      // 重置录音
      stopRecorder() {
        this.rstart = false
        this.pauseStatus = false
        recorder.stop()
        this.resetTime()
      },
      //获取录音文件
      getRecorder() {
        let toltime = recorder.duration //录音总时长
        let fileSize = recorder.fileSize //录音总大小
        //录音结束，获取取录音数据
        let PCMBlob = recorder.getPCMBlob() //获取 PCM 数据
        let wav = recorder.getWAVBlob() //获取 WAV 数据
        let channel = recorder.getChannelData() //获取左声道和右声道音频数据
      },
      //下载wav格式音频
      downWAV() {
        //这里传参进去的时文件名
        this.pauseRecorder()
        this.stopTime()
        recorder.downloadWAV('record_' + this.generateTimeReqestNumber())
        this.stopRecorder()
      },
      // 显示弹窗
      showRecord() {
        this.recordDialog = true
      },
      pad2(n) {
        return n < 10 ? '0' + n : n
      },
      generateTimeReqestNumber() {
        let date = new Date()
        return (
          date.getFullYear().toString() +
          this.pad2(date.getMonth() + 1) +
          this.pad2(date.getDate()) +
          this.pad2(date.getHours()) +
          this.pad2(date.getMinutes()) +
          this.pad2(date.getSeconds())
        )
      },
    },
  }
</script>
<style scoped></style>
